package com.dean.ui.panel.impl;

import com.dean.action.DbQueryAction;
import com.dean.constants.DeanUiConstants;
import com.dean.entity.DataQueryEntity;
import com.dean.entity.DeanResponse;
import com.dean.entity.SysDbConnInfo;
import com.dean.service.DbConnService;
import com.dean.ui.component.ButtonBuilder;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import com.dean.utils.PropertyUtils;
import com.formdev.flatlaf.ui.FlatButtonUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @ClassName DbQueryPanel
 * @Description sql查询页面
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DbQueryPanel extends BasePanel implements DeanPanel{

	private static final Logger logger = LoggerFactory.getLogger(DbQueryPanel.class);
    /**
     * 配置 文件路径
     */
    private final static String INIT_PATH_NAME = DeanUiConstants.INIT_PATH + "dbquery.properties";

    private  DataQueryEntity dataQueryEntity;
    private  JTextArea sqlText;
    private  JLabel connNameLable;
    private  JComboBox<String> connName;
    private  JTextField executeRes;
    private  JLabel pageSizeLabel;
    private  JTextField pageSize;
    private JScrollPane tablelPane;
    private JTable table;
    private JLabel tipLable;

    private  JButton saveCfgBtn;
    private  JButton queryBtn;
    private  JButton exportBtn;


	public void mainUi(){
        connNameLable = new JLabel("connName:");
        UiUtils.setLeftBounds(connNameLable,1);
        panel.add(connNameLable);

        connName = new JComboBox<String>();
        UiUtils.setLeftBounds(connName,1);
        panel.add(connName);

        pageSizeLabel = new JLabel("pageSize:");
        UiUtils.setRightBounds(pageSizeLabel,1);
        panel.add(pageSizeLabel);

        // 默认分页大小
        pageSize = new JTextField("1000");
        UiUtils.setRightBounds(pageSize,1);
        panel.add(pageSize);

        // sql输入窗口
        sqlText = new JTextArea();
        JScrollPane sqlInput = new JScrollPane(sqlText);
        UiUtils.setTextAreaBounds(sqlText,2,4,1,2);
        UiUtils.setTextAreaBounds(sqlInput,2,4,1,2);
        panel.add(sqlInput);

        tipLable = new JLabel("提示信息:");
        UiUtils.setLeftBounds(tipLable,6);
        panel.add(tipLable);

        executeRes = new JTextField("");
        UiUtils.setLeftBounds(executeRes,6,2);
        executeRes.setForeground(Color.RED);
        Font font = new Font("黑体", Font.PLAIN, 20);
        executeRes.setFont(font);
        executeRes.setEditable(false);
        panel.add(executeRes);

        // 执行按钮
        // queryBtn = new JButton("查询");
        queryBtn = ButtonBuilder.primaryButton("查询");
        UiUtils.setRightButtonBounds(queryBtn,7,3);
        panel.add(queryBtn);

       // exportBtn = new JButton("导出查询结果");
        exportBtn = ButtonBuilder.dangerButton("导出查询结果");
        UiUtils.setRightButtonBounds(exportBtn,7,2);
        panel.add(exportBtn);

        saveCfgBtn = ButtonBuilder.greenButton("保存配置信息");
        UiUtils.setRightButtonBounds(saveCfgBtn,7,1);
        panel.add(saveCfgBtn);


        // 查询列表窗口
        table = new JTable();
        tablelPane = new JScrollPane(table);
        table.setShowGrid(true);
        UiUtils.setTableBounds(tablelPane,8);
        panel.add(tablelPane);
    }

    public void mainScript(){
        initProperties();
        exportBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String [] fileTypes = {"EXCEL","CSV","INSERT SQL"};
                JTextField filePath = new JTextField();
                Object[] message = {
                        "导出文件路径:", filePath,
                        "导出文件类型:",
                };
                Object fileType = JOptionPane.showInputDialog(panel,message,"文件导出格式",1,null,fileTypes,null);
                logger.debug("用户选择了导出:{}",fileType);
                if(fileType == null|| "".equals(fileType)){
                    JOptionPane.showMessageDialog(panel, "请选择文件的导出类型", "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if(filePath.getText() == null|| "".equals(filePath.getText())){
                    JOptionPane.showMessageDialog(panel, "文件导出路径不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if(dataQueryEntity == null|| dataQueryEntity.getCode() != 0){
                    JOptionPane.showMessageDialog(panel, "表格数据为空,无法导出", "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                DeanResponse<String> deanResponse =  DbQueryAction.getInstance().exportFile(dataQueryEntity,filePath.getText(),fileType.toString());
                if(deanResponse.getCode() == 0){
                    JOptionPane.showMessageDialog(panel, "FILE SAVE PATH IS :"+deanResponse.getData(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
                }else{
                    JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        queryBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryExecute();
            }
        });


        // 下拉框处理
        DbConnService.getInstance().getConnInfos().forEach(connInfo -> {
            connName.addItem(connInfo.getConnName());
        });


        saveCfgBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(saveProperties()) {
                    JOptionPane.showMessageDialog(panel,"配置信息保存成功", "SUCESS",JOptionPane.INFORMATION_MESSAGE);
                }else {
                    JOptionPane.showMessageDialog(panel,"配置信息保存失败", "ERROR",JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        // 监听键盘事件 只允许输入数字
        pageSize.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                char key = e.getKeyChar();
                Pattern pat = Pattern.compile("[0-9]");
                if (!pat.matcher(String.valueOf(key)).matches()) {
                    e.setKeyChar((char) KeyEvent.VK_CLEAR);
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });

    }

	private void queryExecute(){
        String querySql = sqlText.getText();
        if(querySql == null|| "".equals(querySql)) {
            JOptionPane.showMessageDialog(panel, "执行sql不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(!querySql.trim().toLowerCase().startsWith(DeanUiConstants.START_SELECT_CHAR)) {
            JOptionPane.showMessageDialog(panel, "非法sql，不允许执行", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(querySql.trim().toLowerCase().contains(DeanUiConstants.SEMICOLON)){
            JOptionPane.showMessageDialog(panel, "含有非法字符【;】", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(Integer.parseInt(pageSize.getText())< 1 ){
            JOptionPane.showMessageDialog(panel, "不支持的分页大小", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        dataQueryEntity = DbQueryAction.getInstance().query(initDbConnect(),querySql,Integer.parseInt(pageSize.getText()));
        if(dataQueryEntity.getCode() == 0){
            DefaultTableModel tableModel = new DefaultTableModel(dataQueryEntity.getDatas(),dataQueryEntity.getHeader());
            table.setModel(tableModel);
        }
        executeRes.setText(dataQueryEntity.getCode()+"==="+dataQueryEntity.getMsg());
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setVisible(true);
    }

    /**
     * 保存配置文件
     * @return
     */
	private boolean saveProperties() {
		 Properties properties = new Properties();
         properties.setProperty("pageSize", pageSize.getText());
         properties.setProperty("fieldInput", sqlText.getText());
         return PropertyUtils.saveProperties(INIT_PATH_NAME,properties);
	}

    /**
     * 初始化配置信息
     */
    @Override
    public void initProperties() {
        //初始化基础参数
        Properties properties = PropertyUtils.readProperties(INIT_PATH_NAME);
        if(properties != null){
             pageSize.setText(properties.getProperty("pageSize"));
             sqlText.setText(properties.getProperty("fieldInput"));
        }
	}

    /**
     * 设置数据库连接配置
     */
    private SysDbConnInfo initDbConnect() {
        SysDbConnInfo connectInfo = new SysDbConnInfo();
        connectInfo.setConnName(connName.getSelectedItem().toString());
        return connectInfo;
    }
}
